import { DomService } from './dom.service';

/**
 * 多值属性编辑器组件数据服务
 */
export class UniformEditorDataUtil {

  constructor() { }

  /**
   * 获取组件变量和表单变量数组
   */
  static getVariables(viewModelId: string, domService: DomService): any[] {
    const vars = [];
    // 1、表单变量
    const remoteVars = domService.getRemoteVariables();
    const rootViewModelId = domService.getRootViewModelId();
    const envType = this.getEnvType();
    if(envType !== 'mobileDesigner' ||(envType === 'mobileDesigner' && viewModelId === rootViewModelId)){
      UniformEditorDataUtil._readVariables(remoteVars, vars, 'remote');
    }

    // 2、当前组件的组件变量
    const viewModel = domService.getViewModelById(viewModelId);
    const localVars = domService.getLocaleVariablesByViewModelId(viewModelId);
    for (const localVar of localVars) {
      const children = localVar.children;
      UniformEditorDataUtil._readVariables(children, vars, 'local');
    }

    // 3、根组件的组件变量
    if (viewModel.parent && envType !== 'mobileDesigner') {
      const rootLocalVars = domService.getLocaleVariablesByViewModelId(viewModel.parent);
      for (const rootLocalVar of rootLocalVars) {
        const children = rootLocalVar.children;
        UniformEditorDataUtil._readVariables(children, vars, 'local', true);
      }
    }

    return vars;
  }

  private static getEnvType(){
    // const metadataPath = gsp.ide.getParam('id');
    // if(metadataPath.includes('.mfrm')){
    //   return 'mobileDesigner'
    // }
    return 'designer'

  }

  static _readVariables(children: any, vars: any[], type: string, isFromParent = false) {
    if (!children || !vars) {
      return;
    }
    const envType = this.getEnvType();
    for (const child of children) {
      const variable = child.data;
      const newVar = {
        category: type,
        path: envType !== 'mobileDesigner' && (type === 'remote' || isFromParent) ? 'root-component.' + variable.code : variable.code,
        name: variable.name,
        field: variable.id,
        fullPath: variable.code
      };
      vars.push(newVar);
      UniformEditorDataUtil._readVariables(child.children, vars, type);
    }
  }

  /**
   * 获取控件绑定的字段或变量的编号，作为新生成变量的属性
   * @param propertyData 属性
   * @returns 组件名称（以大驼峰形式返回）
   */
  static getControlName(propertyData: any): string {
    const prop = propertyData.binding && propertyData.binding.path || propertyData.id || '';
    let name = '';
    let upper = true;
    const regx = /^[A-Za-z0-9]$/;
    for (let c of prop) {
      if (regx.test(c)) {
        if (upper) {
          c = c.toUpperCase();
          upper = false;
        }
        name += c;
      } else {
        upper = true;
      }
    }
    return name;
  }

}
